/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include "cmsis_os2.h"
#include "flowmeter.h"
#include "iot_errno.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_demo_def.h"

#define ISR_GPIO 8

static void Get_pulse(char* arg)
{
    if (g_gpioIsrController.controller.callback != NULL) {
        g_gpioIsrController.controller.callback(arg);
    }
}


int Set_Counter(GpioIsrCallback callback,char *arg)
{
    g_gpioIsrController.controller.callback = callback;
    g_gpioIsrController.controller.args = arg;
    IoTGpioRegisterIsrFunc(ISR_GPIO, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_RISE_LEVEL_HIGH, Get_pulse, arg);

    return 0;
}

static int InitMotor()
{
    // 设置GPIO_14的复用功能为普通GPIO
    if (IoTGpioSetFunc(14, IOT_GPIO_FUNC_GPIO_14_GPIO) != 0) {
        RaiseLog(LOG_LEVEL_ERR, "IoTGpioSetFunc IOT_GPIO_FUNC_GPIO_14_GPIO failed! \n");
        return -1;
    }
    // 设置GPIO_14为输出模式
    IoTGpioSetDir(14, IOT_GPIO_DIR_OUT);
    IoTGpioSetOutputVal(14, 1);
    return 0;
}

static int InitGpioIsr()
{
    IoTGpioInit(ISR_GPIO);
    if(IoTGpioSetFunc(ISR_GPIO, IOT_GPIO_FUNC_GPIO_8_GPIO)!= 0){
        RaiseLog(LOG_LEVEL_ERR, "IoTGpioSetFunc IOT_GPIO_FUNC_GPIO_8_GPIO failed! \n");
        return -1;
    }
    // 设置GPIO_8为输入模式
    IoTGpioSetDir(ISR_GPIO, IOT_GPIO_DIR_IN);
    IoTGpioSetPull(ISR_GPIO, IOT_GPIO_PULL_DOWN);
    return 0;
}

int FlowmeterInit(void)
{
    if (InitGpioIsr() < 0) {
        RaiseLog(LOG_LEVEL_ERR, "InitGpioIsr failed! \n");
        return -1;
    }
    if (InitMotor() < 0) {
        RaiseLog(LOG_LEVEL_ERR, "InitMotor failed! \n");
        return -1;
    }
    return 0;
}

int FlowmeterSetMotorStatus(int status)
{
    if (status) {
        IoTGpioSetOutputVal(14, 0);
    } else {
        IoTGpioSetOutputVal(14, 1);
    }
    return 0;
}

void FlowmeterDeinit(void)
{
}
